package com.dkd.manage.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.dkd.common.constant.DkdContants;
import com.dkd.common.exception.ServiceException;
import com.dkd.common.utils.DateUtils;
import com.dkd.manage.domain.Emp;
import com.dkd.manage.domain.Task;
import com.dkd.manage.domain.TaskDetails;
import com.dkd.manage.domain.VendingMachine;
import com.dkd.manage.domain.dto.TaskDTO;
import com.dkd.manage.domain.dto.TaskDetailsDTO;
import com.dkd.manage.domain.vo.TaskVO;
import com.dkd.manage.mapper.TaskMapper;
import com.dkd.manage.mapper.VendingMachineMapper;
import com.dkd.manage.service.IEmpService;
import com.dkd.manage.service.ITaskDetailsService;
import com.dkd.manage.service.ITaskService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 工单Service业务层处理
 *
 * @author luqi
 * @date 2024-09-27
 */
@Service
public class TaskServiceImpl implements ITaskService {
    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    private VendingMachineMapper vendingMachineMapper;
    @Autowired
    private IEmpService empService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ITaskDetailsService taskDetailsService;


    /**
     * 查询工单
     *
     * @param taskId 工单主键
     * @return 工单
     */
    @Override
    public Task selectTaskByTaskId(Long taskId) {
        return taskMapper.selectTaskByTaskId(taskId);
    }

    /**
     * 查询工单列表
     *
     * @param task 工单
     * @return 工单
     */
    @Override
    public List<Task> selectTaskList(Task task) {
        return taskMapper.selectTaskList(task);
    }

    /**
     * 新增工单
     *
     * @param taskDTO 工单
     * @return 结果
     */
    @Override
    public int insertTask(TaskDTO taskDTO) {
        // 校验售货机是否存在
        VendingMachine vm = vendingMachineMapper.selectVendingMachineByInnerCode(taskDTO.getInnerCode());
        if (vm == null) {
            throw new ServiceException("售货机不存在");
        }
        // 判断工单状态
        checkTaskStatus(taskDTO, vm);
        // 校验是否为同类型工单
        checkTaskType(taskDTO);
        // 校验员工
        Emp emp = empService.selectEmpById(taskDTO.getUserId());
        if (emp == null) {
            throw new ServiceException("员工不存在");
        }
        if (!emp.getRegionId().equals(vm.getRegionId())) {
            throw new ServiceException("员工所在区域与售货机所在区域不一致");
        }
        // 保存工单
        Task task = new Task();
        BeanUtils.copyProperties(taskDTO, task);
        task.setTaskStatus(DkdContants.TASK_STATUS_CREATE);
        task.setCreateTime(DateUtils.getNowDate());
        task.setUserName(emp.getUserName());
        task.setAddr(vm.getAddr());
        task.setRegionId(vm.getRegionId());
        // 创建工单编号
        task.setTaskCode(generateTaskCode());
        int taskResult = taskMapper.insertTask(task);

        // 判断是否为补货
        if (taskDTO.getProductTypeId().equals(DkdContants.TASK_TYPE_SUPPLY)) {
        //                 保存工单详情
            List<TaskDetailsDTO> details = taskDTO.getDetails();
            if(CollUtil.isEmpty(details)) {
                throw new ServiceException("工单详情不能为空");
            }
        //     将详情数据转换为工单详情对象dto -> po
            List<TaskDetails> taskDetailsList = details.stream().map(dto -> {
                TaskDetails taskDetails = new TaskDetails();
                BeanUtils.copyProperties(dto, taskDetails);
                taskDetails.setTaskId(task.getTaskId());
                return taskDetails;
            }).collect(Collectors.toList());
        //     批量插入
            taskDetailsService.batchInsertTaskDetails(taskDetailsList);
        }

        return taskResult;
    }

    private String generateTaskCode() {
        // 获取日期yyyymmdd
        String date = DateUtils.getDate().replaceAll("-", "");
        // 设置自增redis
        String key = "dkd.task.code." + date;
        if (!redisTemplate.hasKey(key)) {
            redisTemplate.opsForValue().set(key, 1, Duration.ofDays(1));
            return date + "0001";
        }
        return date + StrUtil.padPre(redisTemplate.opsForValue().increment(key).toString(), 4, "0");
    }

    private void checkTaskType(TaskDTO taskDTO) {
        Task task = new Task();
        task.setInnerCode(taskDTO.getInnerCode());
        task.setProductTypeId(taskDTO.getProductTypeId());
        task.setTaskStatus(DkdContants.TASK_STATUS_PROGRESS);
        List<Task> taskList = taskMapper.selectTaskList(task);
        if (CollUtil.isNotEmpty(taskList)) {
            throw new ServiceException("该售货机存在未完成的工单，请勿重复创建");
        }
    }

    private static void checkTaskStatus(TaskDTO taskDTO, VendingMachine vm) {
        // 1.投放工单，售货机运行状态，报异常
        if (taskDTO.getProductTypeId().equals(DkdContants.TASK_STATUS_CREATE) && DkdContants.VM_STATUS_RUNNING.equals(vm.getVmStatus())) {
            throw new ServiceException("售货机运行中，不能进行投放操作");
        }
        // 2.补货工单，售货机不为运行状态，报异常
        if (taskDTO.getProductTypeId().equals(DkdContants.TASK_TYPE_SUPPLY) && !DkdContants.VM_STATUS_RUNNING.equals(vm.getVmStatus())) {
            throw new ServiceException("售货机未运行，不能进行补货操作");
        }
        // 3.维修工单，售货机不为运行状态，报异常
        if (taskDTO.getProductTypeId().equals(DkdContants.TASK_TYPE_REPAIR) && !DkdContants.VM_STATUS_RUNNING.equals(vm.getVmStatus())) {
            throw new ServiceException("售货机未运行，不能进行维修操作");
        }
        // 4.撤机工单，售货机不为运行状态，报异常
        if (taskDTO.getProductTypeId().equals(DkdContants.TASK_TYPE_REVOKE) && !DkdContants.VM_STATUS_RUNNING.equals(vm.getVmStatus())) {
            throw new ServiceException("售货机未运行，不能进行撤机操作");
        }
    }

    /**
     * 修改工单
     *
     * @param task 工单
     * @return 结果
     */
    @Override
    public int updateTask(Task task) {
        task.setUpdateTime(DateUtils.getNowDate());
        return taskMapper.updateTask(task);
    }

    /**
     * 批量删除工单
     *
     * @param taskIds 需要删除的工单主键
     * @return 结果
     */
    @Override
    public int deleteTaskByTaskIds(Long[] taskIds) {
        return taskMapper.deleteTaskByTaskIds(taskIds);
    }

    /**
     * 删除工单信息
     *
     * @param taskId 工单主键
     * @return 结果
     */
    @Override
    public int deleteTaskByTaskId(Long taskId) {
        return taskMapper.deleteTaskByTaskId(taskId);
    }

    /**
     * 查询工单VO列表
     *
     * @param task
     * @return
     */
    @Override
    public List<TaskVO> selectTaskVOList(Task task) {
        return taskMapper.selectTaskVOList(task);
    }

    /**
     * 取消工单
     * @param task
     * @return
     */
    @Override
    public int cancel(Task task) {
    //     根据taskId查询工单
        Task taskDB = taskMapper.selectTaskByTaskId(task.getTaskId());
        if ( taskDB == null) {
            throw new ServiceException("工单不存在");
        }
        // 判断订单状态，已取消
        if(DkdContants.TASK_STATUS_CANCEL.equals(task.getTaskStatus())) {
            throw new ServiceException("工单已取消");
        }
        // 判断订单状态，已完成
        if(DkdContants.TASK_STATUS_FINISH.equals(task.getTaskStatus())) {
            throw new ServiceException("工单已完成，不能取消");
        }
        task.setTaskStatus(DkdContants.TASK_STATUS_CANCEL);
        task.setUpdateTime(DateUtils.getNowDate());
        return taskMapper.updateTask(task);
    }
}
